/*
 * @Description: 日志管理上下文
 * @Author: Rfan
 * @Date: 2022-09-19 14:08:51
 * @LastEditTime: 2022-09-19 17:48:04
 */

import { createContext, useContext, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  SET_LOG_LIST,
  DELETE_LOG_ITEM,
  SET_SELECTED_ITEM,
  SET_SELECT_LOG_CLASS,
  SET_LOG_TYPE,
  SET_EXPORT_COLS,
  SET_LIST_CONDITION,
  INIT_LIST_CONDITION
} from '../constants';
import { LogReducer } from '../reducers/LogReducer';
import { deleteConvertLog, fetchConvertLogListByPage } from '@/api/log/convert';

const initListCondition = {
  status: ''
};

const initialState = {
  // 日志类型
  logType: 'business',
  // 当前选中的项目
  selectLogNav: 1,

  fondsList: [],
  ATList: [],
  levelList: [],
  // 日志列表
  logList: [],
  // 选中的表格条目
  selectItems: [],
  // 导出日志的列
  exportCols: [],
  // 列表筛选条件
  listCondition: initListCondition,

  // -------- 字典 --------
  // 接收类型列表
  logNavList: [
    {
      id: 3,
      label: '保存与利用日志',
      key: 'saveAndUse'
    },
    { id: 1, pid: 3, label: '格式转换日志', key: 'transform' },
    { id: 2, pid: 3, label: '保存日志', key: 'save' },
    { id: 4, pid: 3, label: '保护日志', key: 'protect' },
    { id: 5, pid: 3, label: '存储日志', key: 'storage' },
    { id: 6, pid: 3, label: '复制日志', key: 'copy' },
    { id: 7, pid: 3, label: '迁移日志', key: 'transfer' },
    { id: 8, pid: 3, label: '检索日志', key: 'search' },
    { id: 9, pid: 3, label: '标引日志', key: 'indexing' },
    { id: 10, pid: 3, label: '利用日志', key: 'use' },
    {
      id: 11,
      key: 'collection',
      label: '收集与整理日志',
      children: [{ id: 12, pid: 11, label: '收集与整理日志', key: 'subCollection' }]
    },
    {
      id: 13,
      key: 'appraisal',
      label: '鉴定与处置日志',
      children: [{ id: 14, pid: 13, label: '收集与整理日志', key: 'subAppraisal' }]
    },
    {
      id: 15,
      key: 'safe',
      label: '档案安全日志',
      children: [{ id: 16, pid: 15, label: '收集与整理日志', key: 'subSafe' }]
    }
  ],

  // 操作日志列表
  operateLogTypeList: [
    {
      id: 1,
      label: '操作日志',
      key: 'operate'
    }
  ],

  // 批次状态列表
  stateList: [
    { id: 200, name: '成功', color: 'green' },
    { id: 500, name: '失败', color: 'red' }
  ]
};

const LogContext = createContext();

const LogContextProvider = (props) => {
  const [state, dispatch] = useReducer(LogReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的日志类型
     */
    setLogType(data) {
      dispatch({ type: SET_LOG_TYPE, data });
    },

    /**
     * @description: 设置选中的日志类别
     */
    setSelectLogClass(data) {
      dispatch({ type: SET_SELECT_LOG_CLASS, data });
    },

    /**
     * @description: 设置选中的日志类别
     */
    setListCondition(data) {
      dispatch({ type: SET_LIST_CONDITION, data });
    },

    /**
     * @description: 设置选中的日志类别
     */
    initListCondition(data) {
      dispatch({ type: INIT_LIST_CONDITION, data: { ...initListCondition, ...data } });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 设置导出表格的表头
     * @param {*} cols
     */
    setExportCols(cols) {
      dispatch({ type: SET_EXPORT_COLS, data: cols });
    },

    /**
     * @description: 获取日志列表方法
     * @param {any} params 参数
     * @return {Promise}
     */
    getCovertLogListFunc(params) {
      return new Promise((resolve, reject) => {
        fetchConvertLogListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_LOG_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除日志条目
     * @param {number|number[]} id
     * @param {string} title
     */
    deleteLogFunc(id, title = '确认删除此日志？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteConvertLog(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_LOG_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  const filters = {
    stateFilter(status) {
      const item = status === 200 ? state.stateList[0] : state.stateList[1];
      return item.name;
    },

    stateColorFilter(status) {
      const item = status === 200 ? state.stateList[0] : state.stateList[1];
      return item.color;
    },

    logNavFilter(id) {
      return state.logNavList.find((item) => item.id === id)?.label || '-';
    }
  };

  return (
    <LogContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </LogContext.Provider>
  );
};

export const useLogContext = () => {
  return useContext(LogContext);
};

export { LogContext, LogContextProvider };
